﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Tray.Interface;

namespace WMS.FC.Domain.Service.Tray
{
    public class CheckTrayStatusService : ServiceBase, ICheckTrayStatusService
    {
        protected readonly ITrayRepository trayRepository;

        public CheckTrayStatusService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITrayRepository trayRepository)
            : base(logger, options, mapper)
        {
            this.trayRepository = trayRepository;
        }

        public async Task<ActionResult<TrayPO>> CheckTrayStatus(string? trayBarcode)
        {
            var result = new ActionResult<TrayPO>("检测托盘状态");
            try
            {
                if (string.IsNullOrWhiteSpace(trayBarcode))
                    return result.ArgumentError("托盘条码不能为空");

                var trayPO = await trayRepository.GetTrayByBarcode(trayBarcode);
                if (trayPO == null)
                    return result.BusinessError($"托盘条码:{trayBarcode},未登录");

                var count = await trayRepository.GetCount<TaskPO>(entity => entity.ContainerBarcode == trayPO.ContainerBarcode);
                if (count > 0)
                    return result.BusinessError($"托盘条码:{trayBarcode},存在任务");

                count = await trayRepository.GetCount<LocationPO>(entity => entity.ContainerBarcode == trayPO.ContainerBarcode);
                if (count > 0)
                    return result.BusinessError($"托盘条码:{trayBarcode},存在库存");

                result.Data = trayPO;
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
